package com.itheima;

import com.itheima.domain.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Demo1 {
    private SqlSession sqlSession;
    Student student = new Student();

    @Before //之前
    public void init() throws IOException {
        //加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");

        //获取SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        //使用builder 创建工厂
        SqlSessionFactory factory = builder.build(is);

        //获取sqlSession
        sqlSession = factory.openSession();

    }

    @After  //之后
    public void release() {
        //手动提交
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }

    //查询
    @Test
    public void findAll() {
        //执行SQL语句
        List<Student> list = sqlSession.selectList("studentMapper.findAll");
        for (Student student : list) {
            System.out.println(student);
        }
    }

    //根据条件查找
    @Test
    public void finById() {
        Student student = sqlSession.selectOne("studentMapper.finById", 2);
        System.out.println(student);
    }

    //累计查找
    @Test
    public void countFind() {
        int count = sqlSession.selectOne("studentMapper.countFind");
        System.out.println(count);
    }

    //# 方式  // select * from xxx where name like ?;
    @Test
    public void findByName() {
        List<Student> name = sqlSession.selectList("studentMapper.findByName", "张");
        for (Student student : name) {
            System.out.println(name);
        }
    }

    @Test
    public void findByName2() {
        List<Student> name = sqlSession.selectList("studentMapper.findByName2", "张");
        for (Student student : name) {
            System.out.println(name);
        }
    }

    //添加
    @Test
    public void save() {
        student.setName("码云");
        student.setAge(20);
        sqlSession.insert("studentMapper.save", student);
    }

    //修改
    @Test
    public void update() {
        student.setId(10);
        student.setName("马云");
        student.setAge(45);
        sqlSession.update("studentMapper.update", student);
    }

    //删除
    @Test
    public void delete() {
        student.setId(10);
        sqlSession.delete("studentMapper.delete", student);
    }

    //添加后查看
    @Test
    public void saveFind() {
        student.setName("马云");
        student.setAge(44);
        System.out.println("保存前"+student);
        sqlSession.insert("studentMapper.saveFind", student);
        System.out.println("保存后"+student);
    }

}
